import {
	mapMutations,
	mapGetters,
	mapActions
} from 'vuex';
import * as index from '@/api/index.js'
export default {
	data() {
		return {
			userinfo:{},
			choice:'',
			text:'',
			loading: false,
			errorShow: false,
			sortAscending: false // 排序方向，false表示降序（最新的在前）
		}
	},
	onPageScroll(e) {
		
	},
	computed: {
		// 从 Vuex 获取订单列表
		list: {
			get() {
				return this.$store.getters.filteredOrderList;
			},
			set(value) {
				// 避免直接修改 computed 属性
			}
		},
		// 获取订单总数
		orderCount() {
			return this.$store.getters.totalOrderCount;
		},
		// 是否显示空状态
		emptyShow() {
			return this.list.length === 0 && !this.loading && !this.errorShow;
		},
		// 获取当前订单筛选状态
		currentOrderStatus() {
			return this.$store.state.currentOrderStatus;
		}
	},
	watch: {
		// 监听用户信息变化
		userinfo: {
			handler(newVal) {
				if (newVal && newVal.userId) {
					this.fetchOrderList();
				}
			},
			immediate: true
		}
	},
	onShow() {
			this.userinfo = uni.getStorageSync('userinfo')
			// 如果已经登录，则获取订单列表
			if (this.userinfo && this.userinfo.userId) {
				this.fetchOrderList();
			} else {
				// 用户未登录时，显示空状态
				this.loading = false;
				this.errorShow = false;
			}
	},
	onLoad(option) {
		this.choice = option.choice
		// 如果有订单状态筛选参数
		if (option.status !== undefined) {
			this.$store.commit('setCurrentOrderStatus', parseInt(option.status));
		}
	},
	// 上拉触底
	onReachBottom() {
			// 分页加载逻辑
			if (!this.loading && this.list.length > 0) {
				// 这里可以添加分页加载的逻辑
			}
	},
	// 下拉刷新
	onPullDownRefresh() {
			this.fetchOrderList().then(() => {
				uni.stopPullDownRefresh();
			}).catch(() => {
				uni.stopPullDownRefresh();
			});
	},
	onNavigationBarButtonTap(e) {
		this.$tools.navigate('/pagesA/user/addAddress/index')
	},
	methods: {
		...mapMutations(['converList', 'setOrderList', 'setCurrentOrderStatus']),
		...mapActions(['fetchOrderList']),
		
		// 处理订单点击事件
		itemBnt(item) {
			// 先检查登录状态
			if (!this.checkLoginStatus()) {
				return;
			}
			// 先存储订单详情到 Vuex
			this.$store.commit('setOrderDetail', item);
			this.$tools.navigate('/pages/user/oder/oderDetli/index?id=' + item.orderNo);
		},
		
		// 手动获取订单列表（兼容旧代码）
		getaddress() {
			this.fetchOrderList();
		},
		
		// 重新定义 fetchOrderList 方法以适配 Vuex action
	fetchOrderList() {
		return new Promise((resolve, reject) => {
			this.loading = true;
			this.errorShow = false;
			
			if (!this.userinfo || !this.userinfo.userId) {
				this.loading = false;
				resolve();
				return;
			}
			
			const params = {
				userId: this.userinfo.userId,
				limit: 99,
				curPage: 1
			};
			
			index.orderList(params).then(res => {
				// 更新 Vuex 中的订单列表
				this.$store.commit('setOrderList', res.page.list || []);
				this.loading = false;
				resolve(res);
			}).catch(error => {
				console.error('获取订单列表失败:', error);
				this.loading = false;
				this.errorShow = true;
				reject(error);
			});
		});
	},
	
	// 跳转到商城页面
	goToShop() {
		this.$tools.navigate('/pages/home/index');
	},
	
	// 重试获取订单
	retryFetch() {
		this.fetchOrderList();
	},
	
	// 检查登录状态
	checkLoginStatus() {
		const userinfo = uni.getStorageSync('userinfo');
		if (!userinfo || !userinfo.userId) {
			uni.showModal({
				title: '提示',
				content: '请先登录',
				showCancel: true,
				cancelText: '取消',
				confirmText: '去登录',
				success: (res) => {
					if (res.confirm) {
						uni.navigateTo({ url: '/pages/login/index' });
					}
				}
			});
			return false;
		}
		return true;
	},
	
	// 根据状态筛选订单
	filterOrdersByStatus(status) {
		// 先检查登录状态
		if (!this.checkLoginStatus()) {
			return;
		}
		this.$store.commit('setCurrentOrderStatus', status);
		// 显示加载状态
		this.loading = true;
		// 延迟一下，让用户看到加载效果
		setTimeout(() => {
			this.loading = false;
		}, 500);
	},
	
	// 按时间排序订单
	sortOrdersByTime(ascending = false) {
		const sortedList = [...this.list].sort((a, b) => {
			const timeA = new Date(a.cjTime || 0).getTime();
			const timeB = new Date(b.cjTime || 0).getTime();
			return ascending ? timeA - timeB : timeB - timeA;
		});
		this.$store.commit('setOrderList', sortedList);
	},
	
	// 切换排序方向
	toggleSort() {
		this.sortAscending = !this.sortAscending;
		this.sortOrdersByTime(this.sortAscending);
	},
		
		detailsBnt(item) {
			if(this.choice) {
				uni.setStorageSync('address', item)
				uni.navigateBack(-1)
			} else {
				this.$tools.navigate('/pages/user/addAddress/index?id=' + item.id)
			}
		},
		// 返回
		returnBnt() {
			uni.navigateBack(-1)
		}
	}
}
